<?php

namespace common\models\shop;

use Yii;
use yii\db\Exception;
use common\helpers\ArrayHelper;
use common\models\member\MemberMarketLog;
use common\logics\CommissionLogic;
use common\models\cso\CsoUser;
use common\models\user\UserCoupon;

/**
 * This is the model class for table "{{%shop_order}}".
 *
 * @property int $id
 * @property string $order_no 订单编号
 * @property int $user_id 用户ID
 * @property string $amount 订单总价（元）
 * @property string $discount 优惠金额（元）
 * @property string $extras 定制费用（元）
 * @property string $express_price 运费（元）
 * @property int $trade_id 交易ID
 * @property string $out_trade_no 支付订单号
 * @property string $pay 交易支付金额
 * @property int $pay_time 支付时间
 * @property string $msg 买家留言
 * @property int $receiver_id 收件信息ID
 * @property int $express_id 发货信息ID
 * @property string $express_code 发货信息ID
 * @property int $express_time 发货信息ID
 * @property int $status 状态
 * @property int $expired_at 过期时间
 * @property int $created_at 创建时间
 * @property int $updated_at 更新时间
 * @property int $deleted_at 删除时间
 */
class ShopOrder extends \common\db\ActiveRecord implements \common\base\BussinessTradeInterface {

    use \common\traits\Constants;

    const STATUS_CLOSE = -2; //已关闭
    const STATUS_CANCEL = -1; //已取消
    const STATUS_DEFAULT = 0; //默认
    const STATUS_ACTIVE = 10; //已提交，待付款
    const STATUS_PAID = 20; //已付款,待发货
    const STATUS_SHIP = 30; //已发货,待收货
    const STATUS_RECEIVED = 40; //已收货,待完成
    const STATUS_COMPLETE = 100; //已完成,待评价
    const STATUS_SUCCESS = 200; //成功订单已关闭
    //
    const EXPIRED_DURTION = 86400 * 3;
    //
    const RECEIVE_AUTO_DURTION = 604800;

    /**
     * {@inheritdoc}
     */
    public static function tableName() {
        return '{{%shop_order}}';
    }

    /**
     * {@inheritdoc}
     */
    public function rules() {
        return [
            [['user_id', 'receiver_id', 'trade_id', 'express_id', 'pay_time', 'express_time', 'status', 'created_at', 'updated_at', 'deleted_at'], 'integer'],
            [['amount', 'extras', 'discount', 'pay', 'express_price'], 'number'],
            [['order_no', 'out_trade_no', 'express_code'], 'string', 'max' => 32],
            [['msg'], 'string', 'max' => 100],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels() {
        return [
            'id' => 'ID',
            'order_no' => '订单编号',
            'user_id' => '用户ID',
            'amount' => '订单总价（元）',
            'extras' => '定制费用（元）',
            'discount' => '优惠金额（元）',
            'trade_id' => '交易ID',
            'out_trade_no' => '支付订单号',
            'pay' => '交易支付金额',
            'pay_time' => '支付时间',
            'msg' => '买家留言',
            'receiver_id' => '收件信息ID',
            'express_id' => '发货信息ID',
            'status' => '状态',
            'expired_at' => '过期时间',
            'created_at' => '创建时间',
            'updated_at' => '更新时间',
            'deleted_at' => '删除时间',
        ];
    }

    public function getGoods() {
        return $this->hasMany(ShopOrderGoods::className(), ['order_id' => 'id']);
    }

    public function getExtrasData() {
        return $this->hasMany(ShopOrderExtras::className(), ['order_id' => 'id']);
    }

    public function getUsedCoupons() {
        return $this->hasMany(UserCoupon::className(), ['model_id' => 'id'])->andWhere([
            'model' => UserCoupon::MODEL_SHOP_ORDER
        ]);
    }

    public function getAddress() {
        return $this->hasOne(\common\models\freight\FreightReceiver::className(), ['id' => 'receiver_id']);
    }

    public function getExpress() {
        return $this->hasOne(\common\models\base\BaseExpress::className(), ['id' => 'express_id']);
    }

    public function getMarketLog() {
        return $this->hasOne(MemberMarketLog::class, ['model_id' => 'id'])->andWhere(['model' => MemberMarketLog::MODEL_SHOP]);
    }

    public function getGoodsAmount() {
        return array_sum(ArrayHelper::getColumn($this->goods, 'goods_number'));
    }

    public function getPrice() {
        $price = $this->amount - $this->discount;
        if ($price > 0) {
            return $price;
        }
        return 0;
    }

    public function getCountdown() {
        $duled = time() - $this->created_at;
        $seconds = self::EXPIRED_DURTION - $duled;
        if ($seconds > 0) {
            return $seconds;
        }
        return 0;
    }

    public function getIsExpired() {
        if ($this->status <= self::STATUS_ACTIVE && $this->getCountdown() <= 0) {
            return true;
        }
        return false;
    }

    public function getIsPay() {
        if ($this->pay_time >= $this->created_at && $this->out_trade_no) {
            return true;
        }
        return false;
    }

    public function getCanCancel() {
        if ($this->isPay) {
            return false;
        }
        if ($this->status > static::STATUS_ACTIVE || $this->status < static::STATUS_DEFAULT) {
            return false;
        }
        return true;
    }

    public function getServiceTips() {
        return '弹出客服介绍内容';
    }

    public function getService() {
        return CsoUser::findOneLink($this->user_id);
    }

    public static function cancel($condition, &$msg) {
        $model = static::findOne($condition);
        if (!$model || !$model->canCancel) {
            $msg = '订单不存在或者订单不能取消';
            return false;
        }
        $model->status = static::STATUS_CANCEL;
        $transaction = Yii::$app->db->beginTransaction();
        try {
            if (!$model->save()) {
                throw new Exception($model->getErrorMsg());
            }
            foreach ($model->goods as $sku) {
                $goods = ShopGoods::findOne($sku->goods_id);
                if (!$goods) {
                    continue;
                }
                $goods->stock += $sku->goods_number;
                if (!$goods->save()) {
                    throw new Exception($goods->getErrorMsg());
                }
            }
            $transaction->commit();
        } catch (Exception $e) {
            $transaction->rollBack();
            $msg = $e->getMessage();
            return false;
        }
        return true;
    }

    public function getTradeTitle() {
        return '购买商品';
    }

    public function getTradeDescription() {
        return '购买商品描述';
    }

    public function generateNo() {
        $from = 1;
        $pcode = 1;
        if ($this->discount) {
            $pcode = rand(2, 9);
        }
        $date = date('Ymd');
        $rules = [
            'paymode' => $pcode,
            'from' => str_pad(dechex($from), 2, "0", STR_PAD_LEFT),
            'date' => substr($date, 2),
        ];
        do {
            $micro = round((microtime(true) - strtotime($date)) * 10000);
            $rules['micro'] = str_pad($micro, 9, 0, STR_PAD_RIGHT);
            $tn = implode($rules);
            $record = static::find()->where(['order_no' => $tn])->exists();
        } while ($record);
        return $this->order_no = $tn;
    }

    public function setPaying() {
        if ($this->status == self::STATUS_DEFAULT) {
            $this->status = static::STATUS_ACTIVE;
        }
    }

    public function getAmount() {
        return $this->amount - $this->discount;
    }

    public function hasRakeBack() {
        if ($this->marketLog) {
            return true;
        }
        return false;
    }

    /**
     * {@inheritdoc}
     * @return ActiveQuery the newly created [[ActiveQuery]] instance.
     */
    public function afterSave($insert, $changedAttributes) {
        if (!$insert && isset($changedAttributes['status']) && $this->status == static::STATUS_RECEIVED) {
            //计算返佣
            CommissionLogic::rakeBack($this->id);
        }
        parent::afterSave($insert, $changedAttributes);
    }

}
